<?php
declare (strict_types = 1);

namespace app\controller;

use think\exception\ValidateException;

use think\facade\Session;
use think\Request;
use app\model\User as UserModel;
use app\model\Topic as TopicModel;
class Topic
{

    protected  $middleware = [//控制器中间件
        \app\middleware\Auth::class 	=> ['only' 	=> ['delete','save'] ],

    ];
    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        try {

            validate([
                'content|博文内容'=>'require|max:2000|token' ])->batch()->check($request->post());

            $userArr=loginUser();
            $user=UserModel::find($userArr['id']);
            $user->topics()->save(['content'=>request()->post('content')]);
            return redirect((string) url('home'))->with('success','博文发表成功~');
        } catch (ValidateException $e) {
            //记录旧的表单输入记录，闪存
            Session::flash('old_topic',$request->post('content'));
            if(!empty($errors=$e->getError()))
            {
                session('errors',$errors);//保存会话信息
                return redirect((string) url('home'));
            }


            // 验证失败
        }
    }


    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        $topic=TopicModel::find($id);
        if($topic &&isMineOpt($topic->user_id)){
            $topic->delete();
            return redirect((string) url('home'))->with('success','你成功删除了一篇博文~');
        }
        else{
            abort(404,'非法操作~');
        }
    }
}
